const axios = require('axios');
const axiosConfig = require('../config/axiosConfig');

// 根据股票编码获取股票最新数据
const getStocksByCode = async (codes) => {
    let stockCodes = codes.map(
        (code) => `${code.startsWith('6') ? 'sh' : 'sz'}${code}`
    );
    const url = 'http://hq.sinajs.cn/list=' + stockCodes.join(',');
    try {
        // 并发请求每个股票的数据
        let response  = await axios.get(url, {
            headers: {
                Referer: 'https://finance.sina.com.cn/',
                'User-Agent':
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        });

        const data = response .data.split("\n");

        const result = {};
        data.forEach(line => {
            if (!line) return;
            const match = line.match(/var hq_str_(.*?)="(.*?)"/);
            if (match) {
                const code = match[1];
                const values = match[2].split(",");
                console.log('values===',values)
                result[code] = {
                    名称: values[0],
                    开盘价: parseFloat(values[1]),
                    当前价: parseFloat(values[3]),
                    最高价: parseFloat(values[4]),
                    最低价: parseFloat(values[5]),
                };
            }
        });
        console.log(result);
        return result;
    } catch (error) {
        console.error('获取股票最新数据失败', error);
        return [];
    }
};

module.exports = {
    getStocksByCode
};
